package cn.sh.yhk.configure.security;

import cn.sh.yhk.mapper.basic.SUserMapper;
import cn.sh.yhk.model.basic.SUser;
import cn.sh.yhk.model.basic.SUserExample;
import cn.sh.yhk.vo.BasicVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IDEA
 * author:Yhk
 * Date:2019/1/9
 * Time:4:09 PM
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Resource
    SUserMapper sUserMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        Long userid = ((MyUserDetails) ((UsernamePasswordAuthenticationToken) authentication).getPrincipal()).getUserId();
        //httpServletRequest.getSession().setAttribute("1asd", username);
        SUser user = new SUser();
        SUserExample ex = new SUserExample();
        ex.createCriteria().andUserIdEqualTo(userid);
        List<SUser> list = sUserMapper.selectByExample(ex);
        if (list.size() > 0) {
            user = list.get(0);
        }
        user.setSessionId(httpServletRequest.getSession().getId());
        sUserMapper.updateByExampleSelective((SUser) list.get(0), ex);
        String username = ((MyUserDetails) ((UsernamePasswordAuthenticationToken) authentication).getPrincipal()).getUsername();
        httpServletResponse.getWriter().write(JSONObject.toJSONString(BasicVo.success("登录成功", username)));
    }

}